import {
	UniAdapter
} from "uniapp-axios-adapter";
import axios from "axios";

export const request = axios.create({
	baseURL: "http://localhost:8003/client-api",
	timeout: 30 * 1000,
	withCredentials: true,
	adapter: UniAdapter,
});

export const getAuthHeader = () => {
	const token = uni.getStorageSync("token");
	if (!token) return {};
	return {
		Authorization: `Bearer ${token}`,
	};
};

request.interceptors.request.use((config) => {
	const cookie = uni.getStorageSync("cookie");
	if (cookie) config.headers.cookie = cookie;
	const token = uni.getStorageSync("token");
	if (token) config.headers = {
		...config.headers,
		...getAuthHeader()
	};
	return config;
});

request.interceptors.response.use((res) => {
	if (!res.config.params?.noStatus && res.data.status !== 200) {
		uni.showToast({
			icon: "error",
			title: res.data.message,
		});
		uni.showToast({
			icon: "fail",
			title: res.data.message,
		});
	}
	if (res.data.status === 401) {
		uni.showToast({
			icon: "fail",
			title: "请先登录",
		});
		setTimeout(() => {
			uni.redirectTo({
				url: "/pages/login/login",
			});
		}, 1500);
	}
	uni.setStorageSync("cookie", res.header["Set-Cookie"]);
	if (res.data.status !== 200 && !res.config.params?.noStatus) {
		return Promise.reject(res.data);
	}
	return res.data;
});